<template>
<div id="goods-image">
    <!-- <form class="label-file" enctype="multipart/form-data" ref="formUpload"> -->
    <div class="label-file">
        <span class="upload-title" @click="handleClickUpload">上传图片</span>
        <!-- accept="image/*" 所有的图片 -->
        <input 
            type="file" 
            id="upload-file" 
            class="upload-file" 
            name='file'
            multiple 
            accept=".png,.jpg,.jpeg"
            ref="inpFile"
            @change="handleUploadImage"
        >
    </div>
    <!-- </form> -->
    <my-canvas-draw-image
        v-if="useCanvas"
        :fileinfo='fileInfo'
        :draw='draw'
    ></my-canvas-draw-image>
    <div class="file-preview">
        <p v-if="newUploadImageList.length === 0" style="height:100%;">
            No files currently selected for upload
        </p>
        <ul 
            v-else 
            class="prew-ul"
            @click="handleClicThisImage" 
        >
            <li 
                v-for="item in newUploadImageList" 
                :key='item.pic'
                class="prew-item"
            >
                <img 
                    :src='`${image_url}/${item.pic}`' 
                    :alt="item.pic | imageName"
                    class="img"
                >
                <span class="upload-success"></span>
                <span class="mark-img"></span>
                <span 
                    class="close-img" 
                    title='点击删除'
                    data-is-delete='true'
                    :data-url='item.pic'
                ></span>
                <span 
                    class="open-prew-img" 
                    title='预览'
                    data-is-open-prew='true'
                    :data-url='item.pic'
                >预览</span>
            </li>
            <li class="prew-item"></li>
            <li class="prew-item"></li>
            <li class="prew-item"></li>
        </ul>
    </div>
    <div v-if='openPrewBool' class="prew-iamge">
        <div class="prew-opt">
            <h3>图片预览 - {{openPrewURL | imageName}}</h3>
            <span class="close-prew-img" @click="openPrewBool=false,openPrewURL=''">×</span>
        </div>
        <img :src="openPrewURL" :alt="openPrewURL | imageName">
    </div>
</div>
</template>

<script>
import { 
    uploadSingleImage, 
    uploadArrayImage
} from '../../config/data'
import { 
    APIROOTURL
} from '../../config/api'
import { messageTip } from '../JS'
export default {
    name: 'goodsImage',
    props: ['goodsinfo'],
    data() {
        return {
            /* --canvas--- */
            useCanvas: false,
            fileInfo: null,
            draw: false,
            /* --canvas--- */
            uploadImageList: [],
            image_url: APIROOTURL,
            openPrewBool: false,
            openPrewURL: '',

        }
    },
    methods: {
        handleClicThisImage(e) {
            if(e.target.constructor === HTMLSpanElement) {
                const url = e.target.dataset.url
                if(e.target.dataset.isDelete === 'true') {
                    let index = this.newUploadImageList.findIndex(item => item.pic === url)
                    this.uploadImageList.splice(index, 1)
                } else if(e.target.dataset.isOpenPrew === 'true') {
                    this.openPrewBool = true
                    this.openPrewURL = `${APIROOTURL}/${url}`
                }
            }
        },
        handleClickUpload(e) {
            this.$refs.inpFile.click()
        },
        async handleUploadImage() {
            // 方式一
            // let form = new FormData(this.$refs.formUpload)
            // let files = form.getAll('file')
            let files = this.$refs.inpFile.files
            if(files.length === 0) return;
            // 方式二
            let form = new FormData()
            files.forEach(item => {
                form.append('image', item)
            })
            // this.fileInfo = files[files.length-1] /* 最后一张 */
            // this.draw = true
            if(![...files].every(item => /^(pn|jp[e]?)g$/.test(item.name.split('.')[1]))) {
                messageTip({content: '上传文件类型被限制（只允许 `.png，.jpg，.jpeg` 格式的图片）'})
                return;
            }
            let result = null
            if(files.length === 1) {
                result = await uploadSingleImage(form)
            } else if(files.length > 1 && files.length <= 8) {
                result = await uploadArrayImage(form)
            } else if(files.length > 8) {
                messageTip({content: '文件上传数量超出限制（一次性上传限制：8）'})
                return;
            }
            messageTip({content: '上传成功'})
            this.uploadImageList = this.uploadImageList.concat(result.data.files)
        }
    },
    computed: {
        newUploadImageList() {
            let list = this.uploadImageList.map(item => {
                return { pic: item.imagePath }
            })
            this.$emit('update:goodsinfo', {
                pics: list
            })
            return list;
        }
    },
    filters: {
        imageName(url) {
            let urlArr = url.split('/')
            return urlArr[urlArr.length - 1].replace(/(\w+)_(.+)_([\d]+)\.((pn|jp[e]?)g)/, '$2.$4');
        }
    }
}
</script>

<style scoped>
#goods-image {
    height: 100%;
}
.label-file {
    height: 50px;
    line-height: 50px;
}
.label-file {
    padding: 0 12px;
    border: 1px dashed rgba(0, 0, 0, 0.2);
    box-sizing: border-box;
}
.upload-title {
    display: inline-block;
    width: 100px;
    height: 32px;
    text-align: center;
    line-height: 32px;
    border: 1px dashed rgba(0, 0, 0, 0.4);
    border-radius: 4px;
    box-sizing: border-box;
    cursor: pointer;
    transition: background-color 0.32s;
}
.upload-title:hover {
    background-color: rgba(0, 0, 0, .1);
}
.upload-file {
    display: none;
}
.file-preview {
    overflow-y: scroll;
    height: calc(100% - 50px - 12px);
    padding: 12px;
    margin-top: 12px;
    text-align: center;
    line-height: 100px;
    border: 1px dashed rgba(0, 0, 0, 0.2);
    box-sizing: border-box;
}
.file-preview::-webkit-scrollbar {
    display: none;
}
.prew-ul {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
}
.prew-item {
    position: relative;
    display: flex;
    min-width: 160px;
    width: 24%;
    margin-top: 12px;
    border-radius: 5px;
    box-sizing: border-box;
}
/* 如果最后一行是3个元素 */
.prew-item:last-of-type:nth-of-type(4n-1) {
    margin-right: calc(24% + 4% / 3)
}
/* 如果最后一行是2个元素 */
.prew-item:last-of-type:nth-of-type(4n-2) {
    margin-right: calc(48% + 8% / 3)
}
.img {
    width: 100%;
    border-radius: 5px;
}
.upload-success {
    overflow: hidden;
    position: absolute;
    top: 0;
    right: 0;
    display: flex;
    width: 20px;
    height: 100%;
    border-radius: 0 5px 5px 0;
    background-color: #57ca48;
    z-index: 2;
}
.upload-success::after {
    content: '\2714';
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
}
.prew-item:hover .upload-success {
    display: none;
}
.mark-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    z-index: -2;
    transition: background-color 0.34s;
}
.prew-item:hover .mark-img {
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1;
}
.close-img, 
.open-prew-img {
    position: absolute;
    top: 50%;
    left: 50%;
    display: block;
    width: 50px;
    height: 50px;
    line-height: 50px;
    margin-top: -25px;
    color: #b70ceb;
    background-color: rgba(255, 255, 255, 0.35);
    font-weight: bold;
    border-radius: 50%;
    z-index: -2;
    cursor: pointer;
}
.close-img {
    margin-left: -55px;
}
.open-prew-img {
    margin-left: 5px;
}
.close-img::before, 
.close-img::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 40px;
    height: 6px;
    margin-top: -3px;
    margin-left: -20px;
    background-color:rgba(255, 255, 255, 0.45);
    transition: background-color 0.34s;
}
.close-img::before {
    transform: rotateZ(45deg);
}
.close-img::after {
    transform: rotateZ(-45deg);
}
.prew-item:hover .close-img, 
.prew-item:hover .open-prew-img {
    z-index: 1;
    transition: background-color 0.34s;
}
.prew-item:hover .close-img:hover, 
.prew-item:hover .open-prew-img:hover {
    background-color: rgba(255, 255, 255, 0.55);
}
.prew-item:hover .close-img:hover::before,
.prew-item:hover .close-img:hover::after {
    background-color: rgba(255, 255, 255, 0.75);
}
.prew-iamge {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 640px;
    height: 370px;
    margin: auto;
    padding: 0 12px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 0 15px #b1b1b1;
    box-sizing: border-box;
    z-index: 10;
}
.prew-opt {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    line-height: 50px;
}
.close-prew-img {
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    border-radius: 50%;
    color: rgb(165, 165, 165);
    font-size: 20px;
    cursor: pointer;
    transition: background-color 0.32s, color 0.32s;
}
.close-prew-img:hover {
    color: rgb(66, 66, 66);
    background-color: rgba(204, 204, 204, 0.5);
}
.prew-iamge img {
    width: 100%;
}
</style>